package org.apache.commons.dbuils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;

import javax.sql.DataSource;

/**
 * @author 付大石
 */
public class AbstractQueryRunner {

    private DataSource dataSource;

    public AbstractQueryRunner(DataSource dataSource) {
        Objects.requireNonNull(dataSource, "dataSource为null");
        this.dataSource = dataSource;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return prepareStatement(prepareConnection(), sql);
    }

    public PreparedStatement prepareStatement(String sql, int autoGenerateKeys) throws SQLException {
        return prepareStatement(prepareConnection(), sql, autoGenerateKeys);
    }

    public PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException {
        return conn.prepareStatement(sql);
    }

    public PreparedStatement prepareStatement(Connection conn, String sql, int autoGeneratedKeys) throws SQLException {
        return conn.prepareStatement(sql, autoGeneratedKeys);
    }

    public Connection prepareConnection() throws SQLException {

        Objects.requireNonNull(dataSource, "dataSource为null");
        return dataSource.getConnection();
    }
    
    /**
     * 填充预处理语句的参数
     * @param pStatement
     * @param params
     * @throws SQLException
     */
    public void fillStatement(PreparedStatement pStatement, Object...params) throws SQLException {
        
        // 参数校验 //
        Objects.requireNonNull(pStatement, "参数pStatement不能为null");
        Objects.requireNonNull(params, "参数params不能为null");
        
        // 填充PreparedStatement的参数 //
        for(int i=0;i<params.length;i++) {
            Object param = params[i];
            if(param == null) {
                pStatement.setNull(i+1,Types.VARCHAR);
            } else {
                pStatement.setObject(i+1,param);
            }
        }
    }
}
